package com.joomlajumpstart.sonicflashcards;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.graphics.drawable.InsetDrawable;
import android.graphics.drawable.PaintDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.Layout;
import android.text.Layout.Alignment;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class SonicFlashcards extends Activity {
	TextView MainCard;
	EditText tvIntro;
	Button btnNext, btnReset, btnPlay;
	InsetDrawable bgdCard1;
	InsetDrawable bgdCard2;
	MediaPlayer mp2;
	ImageView pegImage;
	
	int CardNum;
	int curSide;
	int totalCards;
	String baseDir;
	String curDeck[][];
	MediaPlayer mp;
	Integer[] pegImages;
	MediaPlayer[] audioFiles;
	
    @Override
    public void onCreate(Bundle icicle) {
    	CardNum = 0;
    	curDeck = new String[200][6];
    	totalCards = 0;
        super.onCreate(icicle);
        audioFiles = new MediaPlayer[8];
        audioFiles[0] = MediaPlayer.create(this, R.raw.adios);
        audioFiles[1] = MediaPlayer.create(this, R.raw.llegar);
        audioFiles[2] = MediaPlayer.create(this, R.raw.arriba);
        audioFiles[3] = MediaPlayer.create(this, R.raw.abajo);
        audioFiles[4] = MediaPlayer.create(this, R.raw.poner);
        audioFiles[5] = MediaPlayer.create(this, R.raw.banar);
        audioFiles[6] = MediaPlayer.create(this, R.raw.boton);
        audioFiles[7] = MediaPlayer.create(this, R.raw.nuca);
        doLayout();
    }
    
    public void doLayoutTable() {
		LinearLayout myTL = new LinearLayout(this);
		//appendRow(myTL);
		//appendRow(myTL);
		//LayerDrawable myLayer = new LayerDrawable();
		TextView tempView = addCardDisplay(myTL);
		setContentView(myTL);
    }
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        
        // Parameters for menu.add are:
        // group -- Not used here.
        // id -- Used only when you want to handle and identify the click yourself.
        // title
        menu.add(0, 0, "Add card");
        menu.add(0, 1, "Edit card");
        menu.add(0, 2, "Delete card");
        menu.add(0, 3, "New deck");
        menu.add(0, 3, "Import deck");
        menu.add(0, 4, "Send/Receive Deck");
        menu.add(0, 5, "Preferences");
        menu.add(0, 6, "Delete card");
        menu.add(0, 7, "Delete card");
        return true;
    }
    public boolean onOptionsItemSelected(Menu.Item item){
        switch (item.getId()) {
        case 0:
            showAlert("Add card",0, "Please enter your card information.", "ok", null, false, null);
            return true;
        case 1:
            showAlert("Menu Item Clicked",0, "Please enter your card information.", "ok", null, false, null);
            return true;
        case 2:
            showAlert("Delete card",0, "Are you sure you want to delete this card?", "ok", null, false, null);
            return true;
        }
        return false;
    }
    public TextView addCardDisplay(LinearLayout inTL) {
        //Resources.getDrawable(R.drawable.solid_red);
        TextView label2 = new TextView(this);
        label2.setMinHeight(80);
        label2.setAlignment(Alignment.ALIGN_CENTER);
        label2.setTextSize(18);
        label2.setTypeface(Typeface.DEFAULT_BOLD);
        label2.setGravity(0x10); // Gravity constant; center_vertical

        label2.setText("Red");
        label2.setTextColor(0xFFFFFFFF);

        PaintDrawable tempCard = new PaintDrawable(0xFF0000FF);
        tempCard.setCornerRadius(8);
        bgdCard1 = new InsetDrawable(tempCard,10);
        PaintDrawable tempCard2 = new PaintDrawable(0xFFFFFFFF);
        tempCard2.setCornerRadius(8);
        bgdCard2 = new InsetDrawable(tempCard2,10);
        label2.setBackground(bgdCard1);

        
        inTL.addView(label2,new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));  

        return label2;
    }
    public void doLayoutTableResource() {
    	setContentView(R.layout.table_layout_7);
        //TableLayout myTL = new TableLayout(this);
        final TableLayout myTL = (TableLayout) findViewById(R.id.menu);

        //appendRow(myTL);
        //appendRow(myTL);
        setContentView(myTL);
    }
    private void appendRow(TableLayout table) {
        TableRow row = new TableRow(this);

        TextView label = new TextView(this);
        label.setText("TestText");
        label.setPadding(3, 3, 3, 3);

        TextView shortcut = new TextView(this);
        shortcut.setText("Text2");
        shortcut.setPadding(3, 3, 3, 3);
        shortcut.setAlignment(Layout.Alignment.ALIGN_OPPOSITE);

    	Button testButton = new Button(this);
    	testButton.setText("MyButton");
    	testButton.setMinWidth(200);
    	
    	
        row.addView(testButton, new TableRow.LayoutParams(1));
        row.addView(label, new TableRow.LayoutParams(1));
        row.addView(shortcut, new TableRow.LayoutParams());

        table.addView(row, new TableLayout.LayoutParams());
    }
	public ImageView addImage(Context inContext,int imageNum) {
	    ImageView i = new ImageView(inContext);
	    //i.setImageResource(pegImages[1]);
	    i.setAdjustViewBounds(true);
	    i.setMaxHeight(48);
	    i.setMaxWidth(48);
	    return i;
	    //i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
	    //i.setBackground(android.R.drawable.picture_frame);
	
	}
    public void doLayout() {
    	String text = "";
        LinearLayout myLL = new LinearLayout(this);
        myLL.setOrientation(LinearLayout.VERTICAL);

        // ---------------- Start cardBar
        LinearLayout cardBar = new LinearLayout(this);
        cardBar.setOrientation(LinearLayout.HORIZONTAL);
     
        pegImage = addImage(this,1);
        cardBar.addView(pegImage,new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 

        MainCard = addCardDisplay(cardBar);
       
        myLL.addView(cardBar,new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); 

        /*
        this.MainCard = new Button(this);
        this.MainCard.setText(curDeck[0][0]);
        this.MainCard.setOnClickListener(mFlipcard);
        myLL.addView(this.MainCard,new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); 
        */
        curSide = 0;
        
        this.tvIntro = new EditText(this);
        this.tvIntro.setText("Welcome to Sonic Flashcards");
        TextView tv = new TextView(this);
        tv.setText("Welcome to Sonic Flashcards");

        LinearLayout btnBar = new LinearLayout(this);
        btnBar.setOrientation(LinearLayout.HORIZONTAL);
        
        Button btnFlip = new Button(this);
        btnFlip.setText("Flip");
        btnFlip.setOnClickListener(mFlipcard);
        btnBar.addView(btnFlip,new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 

        btnNext = new Button(this);
        btnNext.setText("Got it!");
        btnNext.setOnClickListener(mNextListener);
        btnBar.addView(btnNext,new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 

        Button btnNope = new Button(this);
        btnNope.setText("Nope, try again");
        btnNope.setOnClickListener(mNextListener);
        btnBar.addView(btnNope,new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 

        btnReset = new Button(this);
        btnReset.setText("Reset");
        btnReset.setOnClickListener(mResetListener);
        btnBar.addView(btnReset,new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 

        /*
        btnPlay = new Button(this);
        btnPlay.setText("Play");
        btnPlay.setOnClickListener(mPlay);
        btnBar.addView(btnPlay,new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
		*/
        
        myLL.addView(btnBar,new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); 

        TextView btnInstructions = new TextView(this);
        btnInstructions.setText("Watch a video tutorial @ http://code.google.com/p/sonicflashcards/");
        //btnPlay.setOnClickListener(mPlay);
        myLL.addView(btnInstructions,new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); 
        
        myLL.addView(this.tvIntro,new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
        myLL.addView(tv,new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
        
        WebView webView = new WebView(this);
        webView.loadData(
                        "<html><body><h1>MyHeading</h1><p>asdsad</p></body></html>",
                        "text/html", "utf-8");
        myLL.addView(webView,new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 

        mp2 = MediaPlayer.create(this, R.raw.adios);
        
        setContentView(myLL);
        tv.setText("Second try");
        // Load the selected deck
        try {
            InputStream is = getAssets().open("decks/spanish_nouns/spanish_nouns.xml");
            int size = is.available();
            
            // Read the entire asset into a local byte buffer.
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            text = new String(buffer);
            
        } catch (IOException e) {
            // Should never happen!
            throw new RuntimeException(e);
        }
        text = parseDeckXML(text);
        updateCardLabel();
        //tv.setText(text);
        tv.setText(this.getDir("spanish_nouns", this.MODE_PRIVATE).toString());
        baseDir = this.getDir("spanish_nouns", this.MODE_PRIVATE).toString();
   }
    public void updateCardLabel() {
        Integer[] pegImages = {
       		   R.drawable.a00,R.drawable.a01,R.drawable.a02,R.drawable.a03,R.drawable.a04,
       		   R.drawable.a05,R.drawable.a06,R.drawable.a07,R.drawable.a08,R.drawable.a09,
       		   R.drawable.a10,R.drawable.a11,R.drawable.a12,R.drawable.a13,R.drawable.a14,
       		   R.drawable.a15,R.drawable.a16,R.drawable.a17,R.drawable.a18,R.drawable.a19,
       		   R.drawable.a20,R.drawable.a21,R.drawable.a22,R.drawable.a23,R.drawable.a24,
       		   R.drawable.a25,R.drawable.a26,R.drawable.a27,R.drawable.a28
       		};
        Integer[] rscAudio = {
   		};
        tvIntro.setText("Card "+(CardNum+1)+" of "+totalCards);
    	MainCard.setText(curDeck[CardNum][curSide]);
    	if(curSide==1) {
    		MainCard.setTextColor(0xFFFFFFFF);
    		MainCard.setBackground(bgdCard1);
    		audioFiles[CardNum].start();
    	} else {
    		MainCard.setTextColor(0xFF000000);
    		MainCard.setBackground(bgdCard2);
    	}
	    pegImage.setImageResource(pegImages[CardNum]);
    }
    View.OnClickListener mNextListener = new OnClickListener() {
        public void onClick(View v) {
        	CardNum++;
        	curSide=0;
        	updateCardLabel();
	        if(CardNum >= totalCards-1) {
        		btnNext.setEnabled(false);
        		btnReset.setEnabled(true);
        	}
        }
    };
    View.OnClickListener mResetListener = new OnClickListener() {
        public void onClick(View v) {
        	CardNum=0;
        	curSide=0;
        	updateCardLabel();
    		btnNext.setEnabled(true);
        }
    };
    View.OnClickListener mFlipcard = new OnClickListener() {
        public void onClick(View v) {
        	if(curSide==0) {
        		curSide=1;
        	} else {
        		curSide=0;
        	}
        	updateCardLabel();
        }
    };

    // To play properly, make sure that you have copied the MP3 files into your emulator.
    // Use abd.exe in your /tools directory. You can create the /decks/spanish_nouns/ directory
    // by executing the shell (adb shell) and then using the mkdir command to create them.
    // Then from the command line, "push" the files with this command:
    // adb push c:\spanish_nouns /decks/spanish_nouns
    View.OnClickListener mPlay = new OnClickListener() {
        public void onClick(View v) {
            mp2.start();

        	String myPath = "/decks/spanish_nouns/"+curDeck[CardNum][4];
        	//String myPath = baseDir + "/"+curDeck[CardNum][4];
        	MediaPlayer mp = new MediaPlayer();
		    if(mp==null) {
		    	btnPlay.setText("NoPlay");
		    }
		    try {
				mp.setDataSource(myPath);
				//mp.prepare();
				mp.prepareAsync();
				mp.start();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
    };
    
    public String parseDeckXML(String inXML)  {
	    Document doc = null;
	    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	    dbf.setIgnoringElementContentWhitespace(true);
	    dbf.setIgnoringComments(true);
	    StringReader reader = new StringReader( inXML );
	    InputSource inputSource = new InputSource( reader );
		try {
			DocumentBuilder db = dbf.newDocumentBuilder();
			doc = db.parse(inputSource); //new File(args[0]); //inXML);
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	    String rootNode = doc.getDocumentElement().getTagName();
	    	//doc.getElementsByTagName("child").item(0).getNodeValue();
	    NodeList tempNL = doc.getElementsByTagName("card");
	    String outStr = "";
	    int faceNum = 1;
	    // Start at -1 so first card loaded will be stored in 0
	    int cardsLoaded = -1;
	    if(dbf.isIgnoringElementContentWhitespace()) {
	    	outStr += "Ignore:Yes\n";
	    }
	    for (int current = 0; current < tempNL.getLength(); current++) {
		    Node cardNode = tempNL.item(current);
		    outStr += "\n"+cardNode.getLocalName()+",";
		    // Get the faces for each card
		    NodeList faceList = cardNode.getChildNodes();
		    for (int j=0;j<faceList.getLength();j++) {
		    	Node tempFace = faceList.item(j);
		    	NodeList faceChildren = tempFace.getChildNodes();
		    	if(tempFace.getLocalName()!=null && faceChildren!=null) {
		    		if(tempFace.getLocalName().equalsIgnoreCase("face1")) {
		    			faceNum=1;
		    		} else {
		    			faceNum=2; 
		    		}
					for(int k=0;k<faceChildren.getLength();k++) {
						Node t = faceChildren.item(k);
						if(t.getLocalName()!=null && t.getChildNodes()!=null) {
							//outStr += "$"+t.getLocalName()+"$";
							if(t.getLocalName().equalsIgnoreCase("t")) {
								if(faceNum==1){
					    			cardsLoaded++;
									outStr += " F:"+cardsLoaded+t.getChildNodes().item(0).getNodeValue();
									curDeck[cardsLoaded][0]=t.getChildNodes().item(0).getNodeValue();
								} else {
									outStr += " B:"+cardsLoaded+t.getChildNodes().item(0).getNodeValue();
									curDeck[cardsLoaded][1]=t.getChildNodes().item(0).getNodeValue();
								}
							} else if(t.getLocalName().equalsIgnoreCase("a")) {
								if(faceNum==1){
									curDeck[cardsLoaded][3]=t.getChildNodes().item(0).getNodeValue();
								} else {
									curDeck[cardsLoaded][4]=t.getChildNodes().item(0).getNodeValue();									
								}
							}
						}
					}
		    	}
			    String junk ="";
		    }
			//if (node instanceof Text) {
				//Text text = (Text) node;
				//String value = text.getNodeValue();
				//if ((value != null) && (value.length() > 0)) {
					//outStr += value;
			//	}
			//}
		}
	    totalCards = cardsLoaded+1;
	    return "hello2 "+rootNode+":"+outStr;
    
    }

 }